package com.mililoan.persist.system.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.poi.ss.formula.functions.T;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.PreparedStatementSetter;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;

import com.mililoan.common.dao.AbstractBaseDao;
import com.mililoan.common.utils.StackTraceUtil;
import com.mililoan.common.utils.Tool;
import com.mililoan.model.system.Function;
import com.mililoan.model.system.Menu;
import com.mililoan.persist.system.ActorRightDao;
import com.mililoan.persist.system.MenuDao;
import com.mililoan.persist.system.UserRightDao;

/**
 * 角色功能表实现类
 * 
 * @author mwei
 *
 */
@Repository("ActorRightDao")
public class ActorRightDaoImpl extends AbstractBaseDao<T> implements ActorRightDao {
	private static final Logger	LOGGER		= LoggerFactory.getLogger(ActorRightDaoImpl.class);

	@Autowired
	private MenuDao				menuDao;	
	@Autowired
	private UserRightDao        userRightDao;

	/**
	 * 根据角色ID获得功能
	 * 
	 * @param actorId
	 *            角色ID
	 * @return
	 */
	public ArrayList<Function> getActorRight(Integer actorId) {
		LOGGER.info("=======getActorRight========");
		JdbcTemplate template = this.getJdbcTemplate();
		final ArrayList<Function> list = new ArrayList<Function>();		
		String sql = "SELECT * FROM SYS_ACTOR_FUNC T WHERE T.ACTOR_ID=?";
		
		try {
			template.query(sql, new Object[] { actorId }, new RowCallbackHandler() {
				public void processRow(ResultSet rs) throws SQLException {
					Function fun = new Function();
					fun.setCode(rs.getInt("FUNC_CODE"));
					fun.setFlag(rs.getString("FLAG"));
					list.add(fun);
				}
			});
		} catch (Exception e) {
			LOGGER.error("--------获得功能时出错------------");
			LOGGER.error("获得功能时出错：", StackTraceUtil.getStackTrace(e));
			return null;
		}
		return list;
	}

	/**
	 * 为角色添加单个权限
	 * 
	 * @param actorId 角色ID
	 * @param fun 权限
	 * @return
	 */
	public boolean addActorRight(final Integer actorId, final Function fun) {
		JdbcTemplate template = this.getJdbcTemplate();
		// 取得新的ID
		Integer newId = new Integer(0);
//		final Integer newId = this.getSeqNextVal("SEQ_ACTOR_FUNC_ID");
		final String sql = "INSERT INTO SYS_ACTOR_FUNC(ACTOR_ID,FUNC_CODE,FLAG) VALUES(?,?,?)";
		try {
			//返回主键
			KeyHolder keyHolder = new GeneratedKeyHolder();
			template.update(new  PreparedStatementCreator(){
				public PreparedStatement createPreparedStatement(Connection con) throws SQLException {					
					PreparedStatement ps = con.prepareStatement(sql, 
								PreparedStatement.RETURN_GENERATED_KEYS);
							ps.setInt(1, actorId);
							ps.setInt(2, fun.getCode());
							ps.setString(3, (null == fun.getFlag()) ? "1" : fun.getFlag());
					return ps;
				}
			},keyHolder);
			//获取主键
			newId = keyHolder.getKey().intValue();
		} catch (Exception e) {
			LOGGER.error("--------为角色添加单个权限时出错------------");
			LOGGER.error(StackTraceUtil.getStackTrace(e));
			return false;
		}
		return true;
	}

	/**
	 * 为角色添加单个权限
	 * 
	 * @param actorId  角色ID
	 * @param funCode  权限code
	 * @return
	 */
	public boolean addActorRight(final Integer actorId, final Integer funCode) {
		Function fun = new Function();
		fun.setCode(funCode);
		fun.setFlag("1");
		return addActorRight(actorId, fun);
	}

	/**
	 * 为角色添加多个权限
	 * 
	 * @param actorId 角色ID
	 * @param funCodes 权限code
	 * @return
	 */
	public boolean addActorRight(Integer actorId, ArrayList<Integer> funCodes) {
		if (null != funCodes && funCodes.size() > 0) {
			Map<String, Integer> existMap = new HashMap<String, Integer>();
			List<Menu> menuList = new ArrayList<Menu>();
			int parentCode = 0;
			
			if (menuList.size() == 0) {
				menuList = menuDao.getAllMenu();
			}
			
			for (int i = 0; i < funCodes.size(); i++) {
				// 查询功能模块所属的父级菜单
				for (int j = 0; j < menuList.size(); j++) {
					if (funCodes.get(i).equals(menuList.get(j).getMenuId())) {
						parentCode = menuList.get(j).getParentMenu();
						break;
					}
				}
				if (null != existMap && existMap.size() > 0) {
					if (parentCode != 0 && !existMap.containsKey(String.valueOf(parentCode))) {
						if (!this.addActorRight(actorId, parentCode)) {
							return false;
						}
						existMap.put(String.valueOf(parentCode), parentCode);
					}
					if (!existMap.containsKey(funCodes.get(i))) {
						if (!this.addActorRight(actorId, funCodes.get(i))) {
							return false;
						}
						existMap.put(String.valueOf(funCodes.get(i)), funCodes.get(i));
					}
				} else {
					if (parentCode != 0) {
						if (!this.addActorRight(actorId, parentCode)) {
							return false;
						}
						existMap.put(String.valueOf(parentCode), parentCode);
					}

					if (!this.addActorRight(actorId, funCodes.get(i))) {
						return false;
					}
					existMap.put(String.valueOf(funCodes.get(i)), funCodes.get(i));
				}
			}
		}
		return true;
	}

	/**
	 * 删除角色权限
	 * 
	 * @param userId
	 *            用户ID
	 * @return
	 */
	public boolean delActorRight(Integer actorId) {
		JdbcTemplate template = this.getJdbcTemplate();
		try {
			String sql = "DELETE FROM SYS_ACTOR_FUNC WHERE ACTOR_ID=?";
			template.update(sql, new Object[] { actorId });
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println(e.getMessage());
			return false;
		}
		return true;
	}

	public boolean delUserFunc(Integer actorId,ArrayList<Integer> actorFuncs) throws Exception {
		boolean flag = true;
		JdbcTemplate template = this.getJdbcTemplate();
		
		//没有的权限需要添加上去
		List userList = template.queryForList("SELECT USER_ID AS UID FROM SYS_USER_FUNC WHERE CODE="+actorId+" AND PTYPE ='A'");		
		if(userList==null || userList.size()==0){	
			return flag;
		}else{
			for(int i=0;i<userList.size();i++){
				HashMap map = (HashMap)userList.get(i);
				Long  id = Tool.parseLong(map.get("UID"));
				userRightDao.addUserActor(id, actorFuncs);
			}
		}
		
		//删除去掉的权限
		List list = template.queryForList("select id from SYS_USER_FUNC where user_id in (select user_id from SYS_USER_FUNC where code="+actorId+" and ptype ='A') "+ 
                                          " and ptype <>'A' and code not in (select FUNC_CODE from SYS_ACTOR_FUNC where ID="+actorId+")");
		if(list==null || list.size()==0){
			return flag;
		}else{
			String ids = "";
			for(int i=0;i<list.size();i++){
				HashMap map = (HashMap)list.get(i);
				String  id = String.valueOf(map.get("id"));
				if(i == (list.size()-1)){
					ids += id;
				}else{
					ids += id + ",";
				}
			}
			try {
				String sql = "DELETE FROM SYS_USER_FUNC WHERE ID in ("+ ids +")";
				template.update(sql, new Object[] {});
			} catch (Exception e) {
				LOGGER.error("--------删除用户角色关联权限时出错------------");
				LOGGER.error(StackTraceUtil.getStackTrace(e));
				return false;
			}
		}		
		
		return flag;
	}
}
